<!-- 添加模板关联票券 -->
<script setup lang="ts">
import { ref, h } from "vue";
import { Back } from "@element-plus/icons-vue";
import {
  ElButton,
  ElCol,
  ElDivider,
  ElDrawer,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInput,
  ElMessage,
  ElRow,
  ElText,
} from "element-plus";

import EnumTag from "@/components/common/EnumTag.vue";
import DialogCouponRuleSetting from "./DialogCouponRuleSetting.vue";
import { ProInputNumber, ProRadioGroup } from "@/modules/package/form";
import ProSelect from "@/modules/package/form/components/ProSelect.vue";

import ApiCoupon from "@/api/coupon";
import useEnum from "@/hooks/useEnum";
import { usePureForm } from "@/hooks/useForm";
import useProTable from "@/hooks/useProTable";
import { EnumCouponCategory, EnumCouponType } from "@/utils/enum";

import { TCoupon } from "@/global";
import { TPackage } from "@/types/global";

const { list: listStatus } = useEnum("EnumStatus");

const { couponSource } = defineProps<{
  couponSource?: any;
}>();

const emits = defineEmits<{
  confirm: [event: TPackage["coupons"][number]];
}>();

// 0 选择票券 1 编辑票券信息
const step = ref(!!couponSource ? 1 : 0);

const { refForm, model, submit } = usePureForm<
  TPackage["coupons"][number] & { couponData: TCoupon }
>(() => emits("confirm", model.value), {
  defaultModel: {
    num: 1,
    sort: 99,
    status: 1,
    ...couponSource,
    rules: [...(couponSource?.rules || [])],
  },
});

/**
 * 提交前校验规则是否正确
 * 1. 检测rules不能为空，为空，提示
 * 2. rules下，每一个rule_type最多只能存在一个，存在重复的rule_type给提示
 */
const beforeSubmit = () => {
  const rules = model.value.rules || [];

  if (rules.length < 1) {
    ElMessage.error("请填写规则");
    return;
  }

  const ruleTypes = rules.map((e) => e.rule_type);
  const uniqueRuleTypes = new Set(ruleTypes);

  if (ruleTypes.length !== uniqueRuleTypes.size) {
    ElMessage.error("时间规则或核销规则重复，请检查");
    return;
  }

  submit();
};

const handleSelectedCoupon = (row: TCoupon) => {
  model.value = {
    ...model.value,
    coupon_id: row.id,
    coupon_name: row.coupon_name,
    rules: [],
    sort: 99,
    num: 1,
    status: 1,

    couponData: row,
  };
  step.value = 1;
};

// 校验规则详情
const ruleValidator = (rule: any, value: any[], fn: any) => {
  console.log(value);
  if (value?.length < 1) {
    return fn(new Error("请填写规则"));
  }

  const index = value.findIndex((e) => !e.rule_type || e.sort <= 0);
  if (index > -1) {
    return fn(new Error("请补全规则"));
  }
  fn();
};

const rules = {
  num: [{ required: true, message: "请填写下发数量" }],
  sort: [{ required: true, message: "请填写排序值" }],
  rules: {
    required: true,
    message: "请补全规则内容",
    validator: ruleValidator,
  },
};

// 表格列
const tableColumns = [
  { label: "票券标题", prop: "coupon_name" },
  { label: "票券副标题", prop: "coupon_subname" },
  {
    label: "票券标签",
    prop: "coupon_type",
    slot: ({ row }: any) =>
      h(EnumTag, {
        isText: true,
        value: row.coupon_type,
        options: EnumCouponType,
      }),
  },
  {
    label: "票券类型",
    prop: "coupon_category",
    slot: ({ row }: any) =>
      h(EnumTag, {
        isText: true,
        value: row.coupon_category,
        options: EnumCouponCategory,
      }),
  },
  {
    label: "操作",
    width: 70,
    slot: ({ row }: any) =>
      h(
        ElButton,
        {
          link: true,
          type: "primary",
          onClick: () => handleSelectedCoupon(row),
        },
        "选择"
      ),
  },
];

const [ProTable] = useProTable({
  fetchUrl: ApiCoupon.list,
  showTableBar: false,
  tableOptions: {
    columns: tableColumns,
  },
  formOptions: {
    formItems: [
      { label: "票券标题", children: { type: ElInput, field: "coupon_name" } },
      {
        label: "票券类型",
        children: {
          type: ProSelect,
          field: "coupon_type",
          props: {
            options: EnumCouponType.map((e) => ({ ...e, disabled: false })),
          },
        },
      },
      // { label: '票券类别', children: { type: ElInput, field: 'coupon_category' } },
    ],
  },
});
</script>

<template>
  <ElDrawer :model-value="true" title="添加权益" size="80%">
    <template #header>
      <div class="flex items-center">
        <template v-if="step == 1">
          <ElIcon :size="24" @click="step = 0">
            <Back />
          </ElIcon>
          <ElDivider direction="vertical" />
        </template>
        <ElText>{{ step ? "设置权益规则" : "选择优惠券" }}</ElText>
      </div>
    </template>

    <template #footer>
      <template v-if="step == 1">
        <ElButton
          type="primary"
          size="large"
          class="w-[120px]"
          @click="beforeSubmit"
          >确定
        </ElButton>
      </template>
    </template>

    <div v-if="step == 1">
      <ElForm ref="refForm" :model="model" :rules="rules" label-width="6em">
        <ElRow>
          <ElCol :span="12">
            <ElFormItem label="权益名称">
              {{ model.coupon_name }}
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="数量" prop="num">
              <ProInputNumber
                v-model="model.num"
                :min="1"
                :max="999"
                :precision="0"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="状态" prop="status">
              <ProRadioGroup v-model="model.status" :options="listStatus" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="排序" prop="sort">
              <ProInputNumber
                v-model="model.sort"
                :min="1"
                :max="9999"
                :precision="0"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElFormItem label="备注" prop="remark">
          <ElInput v-model="model.remark" type="textarea" />
        </ElFormItem>

        <!-- S 规则配置 -->
        <DialogCouponRuleSetting v-model="model.rules" />
        <!-- E 规则配置 -->
      </ElForm>
    </div>

    <ProTable v-else />
  </ElDrawer>
</template>
